package com.onetech.adrewards.free.models;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONObject;

import android.os.Bundle;

import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.config.AppConfig.URLRequestApi;
import com.onetech.adrewards.free.http.APIRequestResult;
import com.onetech.adrewards.free.http.ZuZuHttpRequest;
import com.onetech.adrewards.free.listener.UserIF;
import com.onetech.adrewards.free.objects.UserInfoDTO;

public class UserModel implements UserIF{
	
	private static UserIF _instance;
	private static final Lock createLock=new ReentrantLock();
	
	public UserModel(){
		
	}
	public static UserIF getInstance(){
		if(_instance==null){
			createLock.lock();
			if(_instance==null){
				_instance=new UserModel();
			}
			createLock.unlock();
		}
		return _instance;
	}
	@Override
	public UserInfoDTO getUserInfo(String uId) {
		Bundle params=new Bundle();
		APIRequestResult result=ZuZuHttpRequest.getInstance().getDataFromServer(URLRequestApi.GET_USER_INFO_URL, params);		
		return parserUserInfoFromAPIRequestResult(result);
	}
	private UserInfoDTO parserUserInfoData(JSONObject data){	
//		id: "1",
//		mem_id: "m00001",
//		device_id: "d000001",
//		device_type: "android",
//		imei: "i000001",
//		serial_number: "s000001",
//		user_agent: "android-uuuuuuu",
//		total_coin: "3",
//		created_at: "2014-03-11 07:07:44",
//		updated_at: "2014-03-11 07:07:44"
			
		try {
			UserInfoDTO result=new UserInfoDTO();
			//result.setCreated_at(data.getString("created_at"));
			result.setDevice_id("");
			result.setDevice_type("");
			result.setImei("");
			result.setSerial_number("");
			result.setTotal_coin(data.getString("total_coin"));
			result.setuId(data.getString("mem_id"));
			//result.setUpdated_at(data.getString("updated_at"));
			result.setUser_agent("");
			CommonModel.getInstance().setStore(Cache.ONE_TECH_USER_POINTS, result.getTotal_coin());
			return result;
		} catch (Exception e) {
			return null;
		}
		
	}
	private UserInfoDTO parserUserInfoFromAPIRequestResult(APIRequestResult data){
		try {
			UserInfoDTO user=null;
			
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jsonObject=(JSONObject)data.data;								
				JSONObject jb=jsonObject.getJSONObject("result");
				user=parserUserInfoData(jb);												
			}
			return user;
		} catch (Exception e) {
			return null;
		}
	}
}
